<template>
  <el-container>
    <el-aside width="25%" class="search-and-house-type">
      <!--      对提交预测按钮绑定enter键-->
      <el-form
        @keyup.enter="submitForm"
        label-position="left"
        label-width="110px"
      >
        <div class="section-title">小区名称</div>
        <el-form-item label="小区地址">
          <div class="input-with-required">
            <el-input
              v-model="searchAddress"
              placeholder="输入地址进行搜索"
              @blur="searchLocation"
            ></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>

        <el-divider></el-divider>
        <div class="section-title">地理位置</div>
        <el-form-item label="经度">
          <el-input
            v-model="longitude"
            readonly
            placeholder="生成经度"
          ></el-input>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input
            v-model="latitude"
            readonly
            placeholder="生成纬度"
          ></el-input>
        </el-form-item>
        <el-form-item label="地区名称">
          <el-select
            v-model="districtName"
            filterable
            placeholder="请选择或搜索地区名称"
          >
            <el-option
              v-for="item in districtOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商业区域">
          <el-select
            v-model="businessArea"
            filterable
            placeholder="请选择或搜索商业区域"
          >
            <el-option
              v-for="item in businessAreaOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="社区名称">
          <el-select
            v-model="communityName"
            filterable
            placeholder="请选择或搜索社区名称"
          >
            <el-option
              v-for="item in communityNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-divider></el-divider>
        <!-- 房地产概况区域 -->
        <div class="section-title">房地产概况</div>
        <el-form-item label="总楼层数">
          <div class="input-with-required">
            <el-input v-model.number="totalFloors" type="number"></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="挂牌价格">
          <el-input v-model.number="listingPrice" type="number"></el-input>
        </el-form-item>
        <el-form-item label="建造年份">
          <el-input v-model.number="yearBuilt" type="number"></el-input>
        </el-form-item>
        <el-form-item label="房屋面积">
          <div class="input-with-required">
            <el-input
              v-model.number="buildingArea"
              type="number"
              placeholder="房屋总面积（平方米）"
            ></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="您的价格预估">
          <div class="input-with-required">
            <el-input v-model.number="priceAdjustment" type="number"></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="观看次数">
          <el-input
            v-model.number="viewingCount"
            type="number"
            placeholder="购买者观看次数"
          ></el-input>
        </el-form-item>
        <el-form-item label="关注者数量">
          <el-input
            v-model.number="followersCount"
            type="number"
            placeholder="相关代理人的人员数量"
          ></el-input>
        </el-form-item>
        <el-form-item label="访问者数量">
          <el-input
            v-model.number="visitorsCount"
            type="number"
            placeholder="查看的访问者数量"
          ></el-input>
        </el-form-item>
        <el-form-item label="楼梯数量">
          <div class="input-with-required">
            <el-input
              v-model.number="ladders"
              type="number"
              placeholder="电梯或者楼梯数量"
            ></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="每层住户数">
          <div class="input-with-required">
            <el-input
              v-model.number="houses"
              type="number"
              placeholder="每层独立住房单元的数"
            ></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="厨房总数">
          <div class="input-with-required">
            <el-input v-model.number="kitchens" type="number"></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="卧室总数">
          <div class="input-with-required">
            <el-input v-model.number="bedrooms" type="number"></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="客厅总数">
          <div class="input-with-required">
            <el-input v-model.number="livingrooms" type="number"></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="浴室总数">
          <div class="input-with-required">
            <el-input v-model.number="bathrooms" type="number"></el-input>
            <span class="required">*</span>
          </div>
        </el-form-item>

        <el-divider></el-divider>
        <div class="section-title">建筑属性</div>

        <el-form-item label="房产样式">
          <div class="input-with-required">
            <el-select
              v-model="apartmentType"
              filterable
              placeholder="请选择或搜索房产样式"
            >
              <el-option
                v-for="item in apartmentTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="建筑类型">
          <el-select
            v-model="buildingType"
            filterable
            placeholder="请选择或搜索建筑类型"
          >
            <el-option
              v-for="item in buildingTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房屋朝向">
          <div class="input-with-required">
            <el-select
              v-model="houseOrientation"
              filterable
              placeholder="请选择或搜索房屋朝向"
            >
              <el-option
                v-for="item in houseOrientationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="建筑结构">
          <el-select
            v-model="buildingStructure"
            filterable
            placeholder="请选择或搜索建筑结构"
          >
            <el-option
              v-for="item in buildingStructureOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="取暖方式">
          <el-select
            v-model="heatingMethod"
            filterable
            placeholder="请选择或搜索取暖方式"
          >
            <el-option
              v-for="item in heatingMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="装修状态">
          <div class="input-with-required">
            <el-select
              v-model="renovationStatus"
              filterable
              placeholder="请选择或搜索装修状态"
            >
              <el-option
                v-for="item in renovationStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-form-item label="是否有电梯">
          <div class="input-with-required">
            <el-select
              v-model="elevatorAvailable"
              filterable
              placeholder="请选择或搜索是否有电梯"
            >
              <el-option
                v-for="item in elevatorAvailableOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <span class="required">*</span>
          </div>
        </el-form-item>
        <el-divider></el-divider>
        <!-- 交易与使用区域 -->
        <div class="section-title">交易与使用</div>
        <el-form-item label="房产类型">
          <el-select
            v-model="transactionRights"
            filterable
            placeholder="请选择或搜索房产类型"
          >
            <el-option
              v-for="item in transactionRightsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指定用途">
          <el-select
            v-model="houseUsage"
            filterable
            placeholder="请选择或搜索指定用途"
          >
            <el-option
              v-for="item in houseUsageOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所有权信息">
          <el-select
            v-model="houseOwnership"
            filterable
            placeholder="请选择或搜索所有权信息"
          >
            <el-option
              v-for="item in houseOwnershipOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房龄信息">
          <el-select
            v-model="houseAge"
            filterable
            placeholder="请选择或搜索所有权信息"
          >
            <el-option
              v-for="item in houseAgeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider></el-divider>
        <!-- 楼盘信息区域 -->
        <div class="section-title">楼盘信息</div>
        <el-form-item label="挂牌日期">
          <el-date-picker
            v-model="listingDate"
            type="date"
            placeholder="选择挂牌日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="周围价格">
          <el-input
            v-model.number="neiPrice"
            type="number"
            placeholder="请输入周围平均或典型价格"
          ></el-input>
        </el-form-item>

        <el-divider></el-divider>
        <el-button
          type="primary"
          @click="submitForm"
          style="
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
          "
        >
          生成预测
        </el-button>
        <el-form-item class="transaction-info">
          <p>成交均价: {{ transactionAvgPrice }}元</p>
          <p>成交周期: {{ transactionCycle }}周</p>
        </el-form-item>
      </el-form>
    </el-aside>
    <el-main class="map">
      <div id="all map" class="map-container"></div>
    </el-main>
  </el-container>
</template>


<script>
import axios from 'axios';
import {
  districtData,
  businessAreaData,
  communityNameData,
  apartmentTypeData,
  buildingTypeData,
  houseOrientationData,
  renovationStatusData,
  buildingStructureData,
  heatingMethodData,
  elevatorAvailableData,
  transactionRightsData,
  houseUsageData,
  houseAgeData,
  houseOwnershipData
} from '@/data/data';

export default {
  name: "Map",
  data() {
    return {
      map: null,
      searchAddress: "",

      longitude: "", // 经度
      latitude: "", // 纬度

      districtName: '', // 当前选中的地区名称
      districtOptions: Object.entries(districtData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      businessArea: '', // 当前选中的商业区域
      businessAreaOptions: Object.entries(businessAreaData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      communityName: '', // 当前选中的社区名称
      communityNameOptions: Object.entries(communityNameData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      totalFloors: null, // 建筑物的总楼层数
      listingPrice: null, // 挂牌价格
      yearBuilt: null, // 建筑物建造的年份
      buildingArea: null, // 建筑物的总面积
      priceAdjustment: null, // 价格调整
      viewingCount: null, // 观看次数
      followersCount: null, // 关注者数量
      visitorsCount: null, // 访问者数量
      ladders: null, // 楼梯数量
      houses: null, // 住房单元总数
      kitchens: null, // 厨房总数
      bedrooms: null, // 卧室总数
      livingrooms: null, // 客厅总数
      bathrooms: null, // 浴室总数

      apartmentType: '', // 当前选中的公寓分类
      apartmentTypeOptions: Object.entries(apartmentTypeData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      buildingType: '', // 当前选中的建筑类型
      buildingTypeOptions: Object.entries(buildingTypeData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      houseOrientation: '', // 当前选中的房屋朝向
      houseOrientationOptions: Object.entries(houseOrientationData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      buildingStructure: '', // 当前选中的建筑结构
      buildingStructureOptions: Object.entries(buildingStructureData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      heatingMethod: '', // 当前选中的加热方式
      heatingMethodOptions: Object.entries(heatingMethodData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      renovationStatus: '', // 当前选中的装修状态
      renovationStatusOptions: Object.entries(renovationStatusData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      elevatorAvailable: '', // 当前选中的是否有电梯
      elevatorAvailableOptions: Object.entries(elevatorAvailableData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      transactionRights: '', // 当前选中的权利类型
      transactionRightsOptions: Object.entries(transactionRightsData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      houseUsage: '', // 当前选中的指定用途
      houseUsageOptions: Object.entries(houseUsageData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      houseOwnership: '', // 当前选中的所有权信息
      houseOwnershipOptions: Object.entries(houseOwnershipData).map(([label, value]) => ({
        value: parseInt(value),
        label: label
      })),
      houseAge: '',
      houseAgeOptions: Object.entries(houseAgeData).map(([label, value]) =>({
        value: parseInt(value),
        label: label
      })),
      listingDate: "", // 挂牌日期
      neiPrice: null, // 周围平均或典型价格

      transactionAvgPrice: "获取中...", // 成交均价
      transactionCycle: "获取中...", // 成交周期
    };
  },
  mounted() {
    // 由于API已经在index.html中加载，可以直接初始化地图
    this.initMap();
  },
  methods: {
    initMap() {
      // 确保BMapGL已经加载
      if (typeof window.BMapGL !== "undefined") {
        this.$nextTick(() => {
          this.map = new window.BMapGL.Map("all map", {enableMapClick: false});
          this.map.centerAndZoom(
            new window.BMapGL.Point(104.08153351042, 30.655821878416),
            13
          );
          this.scaleCtrl = new window.BMapGL.ScaleControl();
          this.map.addControl(this.scaleCtrl);
          this.zoomCtrl = new window.BMapGL.ZoomControl();
          this.map.addControl(this.zoomCtrl);
          this.map.enableScrollWheelZoom(true);
        });
      } else {
        console.error("BMapGL is not defined");
      }
    },

    searchLocation() {
      if (this.searchAddress) {
        this.map.clearOverlays();
        var geocoder = new window.BMapGL.Geocoder(); // 创建地理编码实例

        // 使用地理编码服务根据地址获取经纬度
        geocoder.getPoint(
          this.searchAddress,
          (point) => {
            if (point) {
              // 如果成功获取地址对应的经纬度
              this.longitude = point.lng; // 更新经度
              this.latitude = point.lat; // 更新纬度
            } else {
              alert("无法获取该地址的经纬度");
            }
          },
          this.map.getCenter()
        ); // 使用地图中心作为默认位置

        // 如果需要在地图上显示搜索结果，可以继续使用 LocalSearch
        var southWest = new window.BMapGL.Point(102.211227, 30.427339);
        var northEast = new window.BMapGL.Point(104.934234, 31.095268);
        var bounds = new window.BMapGL.Bounds(southWest, northEast);

        var localSearch = new window.BMapGL.LocalSearch(this.map, {
          onSearchComplete: (results) => {
            if (localSearch.getStatus() === window.BMAP_STATUS_SUCCESS) {
              for (var i = 0; i < results.getCurrentNumPois(); i++) {
                var poi = results.getPoi(i);
                var marker = new window.BMapGL.Marker(poi.point);
                this.map.addOverlay(marker);
              }
              if (results.getPoi(0)) {
                this.map.centerAndZoom(results.getPoi(0).point, 16);
              }
            } else {
              alert("未找到结果");
            }
          },
        });
        localSearch.searchInBounds(this.searchAddress, bounds);
      }
    },
    // 提交数据
    submitForm() {
      // 检查小区地址是否填写
      if (!this.searchAddress.trim()) {
        this.$message({
          type: "error",
          message: "小区地址为必填项",
        });
        return; // 阻止表单提交
      }
      // 检查是否有电梯是否选择
      if (this.totalFloors === null) {
        this.$message({
          type: "error",
          message: "请选择总楼层",
        });
        return; // 阻止表单提交
      }
      // 检查是否有电梯是否选择
      if (this.buildingArea === null) {
        this.$message({
          type: "error",
          message: "请填写房屋面积",
        });
        return; // 阻止表单提交
      }
      // 检查是否有电梯是否选择
      if (this.ladders === null) {
        this.$message({
          type: "error",
          message: "请填写电梯或者楼梯数量",
        });
        return; // 阻止表单提交
      }
      // 检查是否有电梯是否选择
      if (this.houses === null) {
        this.$message({
          type: "error",
          message: "请填写每层独立单元住户数",
        });
        return; // 阻止表单提交
      }
      // 检查是否有电梯是否选择
      if (this.kitchens === null) {
        this.$message({
          type: "error",
          message: "请填写厨房数",
        });
        return; // 阻止表单提交
      }
      // 检查是否有电梯是否选择
      if (this.elevatorAvailable === null) {
        this.$message({
          type: "error",
          message: "请选择是否有电梯",
        });
        return; // 阻止表单提交
      }
      if (this.bedrooms === null) {
        this.$message({
          type: "error",
          message: "请填写卧室数",
        });
        return; // 阻止表单提交
      }
      if (this.livingrooms === null) {
        this.$message({
          type: "error",
          message: "请填写客厅数",
        });
        return; // 阻止表单提交
      }
      if (this.bathrooms === null) {
        this.$message({
          type: "error",
          message: "请填写浴室数",
        });
        return; // 阻止表单提交
      }
      if (this.priceAdjustment === null) {
        this.$message({
          type: "error",
          message: "请填写您的价格预估",
        });
        return; // 阻止表单提交
      }
      if (this.renovationStatus === null) {
        this.$message({
          type: "error",
          message: "请选择装修状态",
        });
        return; // 阻止表单提交
      }
      if (this.houseOrientation === null) {
        this.$message({
          type: "error",
          message: "请选择房屋朝向",
        });
        return; // 阻止表单提交
      }

      // 构建要发送到后端的数据对象
      const formData = {
        searchAddress: this.getFieldValue(this.searchAddress),
        longitude: this.getFieldValue(this.longitude),
        latitude: this.getFieldValue(this.latitude),
        districtName: this.getFieldValue(this.districtName),
        businessArea: this.getFieldValue(this.businessArea),
        communityName: this.getFieldValue(this.communityName),
        totalFloors: this.getFieldValue(this.totalFloors),
        listingPrice: this.getFieldValue(this.listingPrice),
        yearBuilt: this.getFieldValue(this.yearBuilt),
        buildingArea: this.getFieldValue(this.buildingArea),
        priceAdjustment: this.getFieldValue(this.priceAdjustment),
        viewingCount: this.getFieldValue(this.viewingCount),
        followersCount: this.getFieldValue(this.followersCount),
        visitorsCount: this.getFieldValue(this.visitorsCount),
        ladders: this.getFieldValue(this.ladders),
        houses: this.getFieldValue(this.houses),
        kitchens: this.getFieldValue(this.kitchens),
        bedrooms: this.getFieldValue(this.bedrooms),
        livingrooms: this.getFieldValue(this.livingrooms),
        bathrooms: this.getFieldValue(this.bathrooms),
        apartmentType: this.getFieldValue(this.apartmentType),
        buildingType: this.getFieldValue(this.buildingType),
        houseOrientation: this.getFieldValue(this.houseOrientation),
        renovationStatus: this.getFieldValue(this.renovationStatus),
        elevatorAvailable: this.getFieldValue(this.elevatorAvailable),
        transactionRights: this.getFieldValue(this.transactionRights),
        houseUsage: this.getFieldValue(this.houseUsage),
        houseOwnership: this.getFieldValue(this.houseOwnership),
        buildingStructure: this.getFieldValue(this.buildingStructure),
        heatingMethod: this.getFieldValue(this.heatingMethod),
        houseAge: this.getFieldValue(this.houseAge),
        neiPrice: this.getFieldValue(this.neiPrice),
        listingDate: this.getFieldValue(this.listingDate)
      };


      // 发送请求到后端
      axios.post("/api/handle_data/", formData)  //注意：此处需要添加
        .then((response) => {
          // 处理响应
          if (response.data.status === 'success') {
            // 更新成交均价和成交周期
            this.transactionAvgPrice = response.data.transactionAvgPrice;
            this.transactionCycle = response.data.transactionCycle;
            this.$message.success("数据提交成功");
          } else {
            this.$message.error("数据提交失败1");
          }
        })
        .catch((error) => {
          // 处理错误
          this.$message.error("数据提交失败2");
        });

    },
    getFieldValue(field) {
      return field !== undefined && field !== null ? field : -1;
    },
  },
};


</script>


<style scoped>
.search-and-house-type {
  padding: 20px;
  height: 100vh; /* 侧边栏高度充满视口 */
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.map-container {
  height: 100vh;
  width: 100%;
}

.map {
  padding: 0px;
}

.transaction-info {
  margin-top: 20px;
}

.input-with-required {
  display: flex;
  align-items: center; /* 垂直居中 */
}

.required {
  color: red;
  margin-right: 5px; /* 与输入框之间的间距 */
  font-size: 14px; /* 根据需要调整字体大小 */
  line-height: inherit; /* 继承行高 */
}
</style>
